package com.five.matebook.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.five.filesync.FileDownloaderRequest;
import com.five.filesync.FileListRequest;
import com.five.filesync.MdnsDisovery;
import com.five.filesync.OnNetCallback;
import com.five.matebook.R;
import com.five.matebook.ServerDiscover;
import com.five.matebook.activity.config.ConfigDataBean;
import com.five.matebook.activity.config.StroageConfig;
import com.five.matebook.activity.db.DbHelper;
import com.five.matebook.activity.income.IncomeColume;
import com.five.matebook.activity.matebook.MateBookManager;
import com.five.matebook.activity.matebook.Matebook;
import com.five.matebook.activity.outcome.OutcomeColume;
import com.five.matebook.utils.DateUtils;
import com.five.matebook.utils.DeviceUtils;

import java.io.File;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

public class DbInitActivity extends Activity {

    private static final String TAG = DbInitActivity.class.getSimpleName();
    public static final String ACTION_AUTOSYNC = "autoSync";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_db_init);
        if (ACTION_AUTOSYNC.equals(getIntent().getAction())) {
            onClick_SycnFromServer(null);
        }
    }

    public void onClick_NewLocalDb(View v) {
        new AlertDialog.Builder(this)
                .setTitle("警告")
                .setMessage("本地新建账本，服务器之前备份将会失效，是否继续？")
                .setPositiveButton("确认新建", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        createAndChooseDefaultMatebook(null, true);
                    }
                }).setNegativeButton("尝试从服务器同步", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        onClick_SycnFromServer(null);
                    }
                }).show();
    }

    private ProgressDialog dialog;
    public synchronized void onClick_SycnFromServer(View v) {
        if (dialog != null) {
            return;
        }
        final ConfigDataBean config = StroageConfig.get(getApplicationContext());
        final MateBookManager mateBookManager = config.getMateBookManager();
        if (config.isAdmin()) {
            mateBookManager.clear();
        }

        dialog = new ProgressDialog(this);
        dialog.setCancelable(false);
        dialog.setMessage("正在查找matebook服务器...");
        dialog.show();
        ServerDiscover.getInstance(getApplicationContext()).startDiscover(new MdnsDisovery.OnMdnsCallback() {
            @Override
            public void onServiceDiscoverd(InetAddress addr, int port) {

                new FileListRequest(addr, port, "matebook", new OnNetCallback() {
                    @Override
                    public void onResult(boolean successed, Object extra) {
                        if (!successed) {
                            // TODO: 2024/1/30
                            onFailed("获取matebook列表失败");
                            return;
                        }
                        List<String> fileList = (List<String>) extra;
                        if (fileList.size() == 0) {
                            // 服务器没有备份, 创建新的
                            createAndChooseDefaultMatebook("服务器没有备份，已在本机创建默认账本", true);
                            return;
                        }
                        dialog.setMessage("正在下载备份的数据库文件...");
                        {
                            expectedDownloadNum = 0;
                            downloadResult = true;
                            downloadnum = 0;
                        }

                        List<FileDownloaderRequest> downloaderRequestList = new ArrayList<>();
                        for (String s : fileList) {
                            Matebook b = Matebook.getMatebook(s);
                            if (b == null)  continue;
                            if (config.isAdmin()) {
                                // 管理员只查看别人的，不看自己的
                                if (b.isMine())    continue;
                            } else {
                                if (!b.isMine())    continue;
                            }
                            expectedDownloadNum ++;
                            mateBookManager.addMatebook(b.getId(), b.getAlias());
                            File local = DbHelper.getDbFile(getApplicationContext(), b.getFileName());
                            Log.d(TAG, "start download: %s" + local.getAbsolutePath());
                            FileDownloaderRequest downloader = new FileDownloaderRequest(addr, port, "matebook", local, new OnNetCallback() {
                                @Override
                                public void onResult(boolean successed, Object extra) {
                                    onDownloadResult(successed);
                                }
                            });
                            downloaderRequestList.add(downloader);
                        }

                        if (expectedDownloadNum == 0) {
                            // 数据库上没有备份的文件
                            dialog.dismiss();
                            if (!config.isAdmin()) {
                                createAndChooseDefaultMatebook("server端没有备份，已在本机创建默认账本", true);
                            } else {
                                Toast.makeText(getApplicationContext(), "没有找到其他的账本记录哦", Toast.LENGTH_SHORT).show();
                                config.toggleAdmin();
                                startActivity(new Intent(getApplicationContext(), MainActivity.class));
                            }
                            return;
                        }

                        for (FileDownloaderRequest r : downloaderRequestList) {
                            r.execute();
                        }
                    }
                }).execute();

                Log.d(TAG, "onServiceDiscoverd()");
            }

            @Override
            public void onServiceNotFound(String serverName) {
                onFailed("没有找到matebook服务器，可以回家再试");
            }
        });
    }

    private int expectedDownloadNum;
    private volatile int downloadnum = 0;
    private boolean downloadResult;
    private synchronized void onDownloadResult(boolean succesed) {
        downloadResult &= succesed;
        if (++downloadnum >= expectedDownloadNum) {
            if (downloadResult) {
                // download successed
                dialog.dismiss();
                dialog = null;
                StroageConfig.get(getApplicationContext()).getMateBookManager().chooseMatebook(getApplicationContext(), 0);
                new AlertDialog.Builder(DbInitActivity.this)
                        .setMessage("数据库文件下载成功")
                        .setPositiveButton("真棒", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent it = new Intent(DbInitActivity.this, MainActivity.class);
                                startActivity(it);
                                DbInitActivity.this.finish();
                            }
                        })
                        .setCancelable(false)
                        .show();
            } else {
                // download failed
                StroageConfig.get(getApplicationContext()).getMateBookManager().getMatebookList().clear();
                onFailed("文件下载失败");
            }
        }
    }

    private void onFailed(String reason) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dialog.dismiss();
                dialog = null;
                new AlertDialog.Builder(DbInitActivity.this)
                        .setMessage(reason)
                        .setPositiveButton("我知道了", null)
                        .show();
            }
        });
    }


    private void createAndChooseDefaultMatebook(String extra, boolean needReturnMainActivity) {
        Log.d(TAG, "createAndChooseDefaultMatebook()");
        Matebook m = StroageConfig.get(getApplicationContext()).getMateBookManager().generateDefaultMatebook();
        StroageConfig.get(getApplicationContext()).getMateBookManager().chooseMatebook(getApplicationContext(), m);
        StroageConfig.save(getApplicationContext());

        if (!TextUtils.isEmpty(extra)) {
            new AlertDialog.Builder(DbInitActivity.this)
                    .setMessage(extra.toString())
                    .setPositiveButton("知道了", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (needReturnMainActivity) {
                                Intent it = new Intent(DbInitActivity.this, MainActivity.class);
                                startActivity(it);
                                DbInitActivity.this.finish();
                            }
                        }
                    })
                    .setCancelable(false)
                    .show();
        } else if (needReturnMainActivity) {
            Intent it = new Intent(DbInitActivity.this, MainActivity.class);
            startActivity(it);
            DbInitActivity.this.finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        StroageConfig.save(getApplicationContext());
    }
}
